/*
 * Copyright (c) 2008 Anshuman Manur <anshuman.manur@gmail.com>,
 * Lavanya Shastri <lavanya.shastri@gmail.com>
 * 
 * This file is part of Andronova.
 * 
 * Andronova is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Andronova is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *  
 * You should have received a copy of the GNU General Public License
 * along with Andronova.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * This file may use the functionality provided by the library
 * jid3lib version 0.5.4 (<http://sourceforge.net/projects/javamusictag/>).
 * jid3lib and its uses are covered by GNU Lesser General Public License.
 * 
 */

package com.googlecode.andronova;

import org.farng.mp3.id3.AbstractID3v2;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.KeyEvent.Callback;
import android.view.Menu.Item;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.googlecode.andronova.helper.Song;


public class PlayScreen extends Activity implements Callback{
	
	private Handler mHandler;
	  
	private static final String MITEM_NAME_TAGEDITOR = "Tag Editor";
	private static final String MITEM_NAME_LYRICS = "Lyrics";
	private static final String MITEM_NAME_LIBRARY = "Library";
	private static final String MITEM_NAME_PLAYLIST = "PlayList";
	private static final String MITEM_NAME_HELP = "Help";
	private static final String MITEM_NAME_CREDITS = "Credits";

	private static final int MITEM_ID_TAGEDITOR = 0;
	private static final int MITEM_ID_LYRICS = 1;
	private static final int MITEM_ID_LIBRARY = 2;
	private static final int MITEM_ID_PLAYLIST = 3;
	private static final int MITEM_ID_HELP = 4;
	private static final int MITEM_ID_CREDITS = 5;
	
	private ImageView play_pause;
    private ImageView next_song;
    private ImageView prev_song;
    
    private TextView artistTV;
    private TextView albumTV;
    private TextView titleTV;
    
    private boolean paused;
    
    public static boolean changed = false;
	
	public static final int PICK_SONG = 1;
	public static final int EDIT_TAG = 2;
	public static final int SET_PATH = 3;
	
	public static final String WARNING = "Warning";
	public static final String ERROR = "Error";
	
	private static Context ctx;
	
    @Override
    public void onCreate(Bundle icicle) {        
    	super.onCreate(icicle);
        setContentView(R.layout.ps_new);
        
        setTitle("AndroMedia");
        
        play_pause = (ImageView)findViewById(R.id.play_pause);
        next_song = (ImageView)findViewById(R.id.next_song);
        prev_song = (ImageView)findViewById(R.id.prev_song);
        
        ctx = this;

    	artistTV = (TextView) findViewById(R.id.artist_tv);
    	albumTV = (TextView) findViewById(R.id.album_tv);
    	titleTV = (TextView) findViewById(R.id.title_tv);
    	
    	mHandler = new MyHandler();
    	Playback.playScreenHandler = mHandler;
       

//LISTENER FOR NEXT_SONG
		
		next_song.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				if(Playback.pbOrganiser==null || !Playback.pbOrganiser.isPlaying())
					return;
				
				new Thread(new Runnable() {
					public void run() {
						Intent i = new Intent(ctx,  Playback.class);
						Bundle b = new Bundle();
						b.putInt(Playback.ACTION, Playback.ACTION_NEXT);
						startService(i, b);
						
						mHandler.postDelayed(new Runnable() {
							public void run() {
								while(!changed) {
									try {
										Thread.sleep(1000);
									}
									catch(InterruptedException e) {
										return;
									}
								}
								updateScreenInfo();
								changed = false;
							}
						}, 2000);
					}
				}).start();
			}			
		});
		
		prev_song.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {	
				if(Playback.pbOrganiser==null || !Playback.pbOrganiser.isPlaying())
					return;
				new Thread(new Runnable() {
					public void run() {
						Intent i = new Intent(ctx,  Playback.class);
						Bundle b = new Bundle();
						b.putInt(Playback.ACTION, Playback.ACTION_PREV);
						startService(i, b);
					}
				}).start();
				mHandler.postDelayed(new Runnable() {
					public void run() {
						while(!changed) {
							try {
								Thread.sleep(1000);
							}
							catch(InterruptedException e) {
								return;
							}
						}
						updateScreenInfo();
						changed = false;
					}
				}, 2000);
			}
		});
	
		play_pause.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(Playback.pbOrganiser == null)
					return;
				final boolean playing = Playback.pbOrganiser.isPlaying();
				if(playing)
					play_pause.setImageResource(R.drawable.andro_play);
				else
					play_pause.setImageResource(R.drawable.andro_pause);
				
				new Thread(new Runnable() {
					public void run() {
						if(playing) {
							Intent i = new Intent(ctx,  Playback.class);
							Bundle b = new Bundle();
							b.putInt(Playback.ACTION, Playback.ACTION_PAUSE);
							startService(i, b);
						}
						else {
							Intent i = new Intent(ctx,  Playback.class);
							Bundle b = new Bundle();
							b.putInt(Playback.ACTION, Playback.ACTION_RESUME);
							startService(i, b);
						}
					}
				}).start();
			}
		});
    }
    
    private void updateScreenInfo() {
    	if(Playback.pbOrganiser == null) return;
    	Song s = Playback.pbOrganiser.getCurrentSong();
    	String title, artist, album;
    	if(s != null) {
    		AbstractID3v2 tag = s.getID3v2Tag();
    		if(tag == null) {
    			title = s.getMp3file().getName();
    			artist = "";
    			album = "";
    		}
    		else {
    			title = tag.getSongTitle();
    			if(tag.equals(""))
    				title = s.getMp3file().getName();
    			album = tag.getAlbumTitle();
    			artist = tag.getLeadArtist();
    			if(artist.equals(""))
    				artist = "Unknown";
    		}
    	}
    	else
    		return;

    	if(titleTV.hasWindowFocus()) {
    		titleTV.setText(title);
    		albumTV.setText(album);
    		artistTV.setText(artist);
    	}
    }

    //Menu creation and reaction
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		super.onCreateOptionsMenu(menu);
 		
 		menu.add(0,  MITEM_ID_TAGEDITOR,  MITEM_NAME_TAGEDITOR,  
 				R.drawable.andro_tageditor);
 		menu.add(0,  MITEM_ID_LYRICS,  MITEM_NAME_LYRICS,  
 				R.drawable.andro_lyrics);
 		menu.add(0,  MITEM_ID_LIBRARY,  MITEM_NAME_LIBRARY, 
 				R.drawable.andro_library);
 		menu.add(0,  MITEM_ID_PLAYLIST,  MITEM_NAME_PLAYLIST,  
 				R.drawable.andro_playlist);
 		menu.add(0,  MITEM_ID_HELP,  MITEM_NAME_HELP,  
 				R.drawable.andro_help);
 		menu.add(0,  MITEM_ID_CREDITS, MITEM_NAME_CREDITS,
 				R.drawable.andro_credits);
 	
 		return true;
 	}

    @Override
 	public boolean onOptionsItemSelected(Item item) {
 		super.onOptionsItemSelected(item);
 		
 		switch(item.getId()) {		 	
 		case MITEM_ID_TAGEDITOR:
			if(Playback.pbOrganiser != null) {
				TagEditor.s = Playback.pbOrganiser.getCurrentSong();
				Intent a = new Intent(this, TagEditor.class);
				startSubActivity(a, EDIT_TAG);
			}
			return true;
			
 		case MITEM_ID_LYRICS:
 			Intent b = new Intent(this, Lyrics.class);
 			startActivity(b);
 			return true;
 			
 		case MITEM_ID_LIBRARY:
 			Intent c = new Intent(this, LibraryActivity.class);
 			startSubActivity(c, PICK_SONG);
 			return true;
 			
 		case MITEM_ID_PLAYLIST:
 			Intent d = new Intent(this, PlaylistEditor.class);
 			startSubActivity(d, PICK_SONG);
 			return true;
 		
 		case MITEM_ID_HELP:
 			Help.CALLING_ACTIVITY = Help.PLAYSCREEN;
 			Intent e = new Intent(this, Help.class);
 			startActivity(e);
 			return true;
 			
 		case MITEM_ID_CREDITS:
 			Intent i99 = new Intent(this,  Credits.class);
 			startActivity(i99);
 			return true;
 		}
 		return false;
 	}
    
    private class MyHandler extends Handler {    	
    	public void handleMessage(Message msg) {
    		if(paused)
    			return;
    		else {
    			updateScreenInfo();
    		}
    	}    	
    }
    

	@Override
	protected void onResume() {
		super.onResume();
		paused = false;
		mHandler.postDelayed(new Runnable() {
			public void run() {
				updateScreenInfo();
			}
		}, 3000);			
	}

	@Override
	protected void onPause() {
		super.onPause();
		paused = true;
		if(Playback.pbOrganiser == null)
			return;
		if(!Playback.pbOrganiser.isPlaying()) {
			Intent i = new Intent(this, Playback.class);
			Bundle b = new Bundle();
			b.putInt(Playback.ACTION, Playback.ACTION_STOP);
			startService(i, b);
		}			
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			String data, Bundle extras) {
		super.onActivityResult(requestCode, resultCode, data, extras);
		
		if(requestCode == PICK_SONG) {
			if(resultCode == RESULT_OK) {
				Intent i = new Intent(this, Playback.class);
				Bundle b = new Bundle();
				b.putInt(Playback.ACTION, Playback.ACTION_INIT);
				startService(i, b);
				play_pause.setImageResource(R.drawable.andro_pause);
				mHandler.postDelayed(new Runnable() {
					public void run() {
						updateScreenInfo();
					}
				}, 10000);
			}
		}
		else if(requestCode == EDIT_TAG) {
			if(resultCode == RESULT_OK) {
				mHandler.postDelayed(new Runnable() {
					public void run() {
						updateScreenInfo();
					}
				}, 3000);
			}
		}
	}
}//Activity